#! /usr/bin/perl -w

use threads;
use threads::shared;
use strict;

$|++;
my $cnt : shared = 0;

for ( 1..10 ) {
    threads->new( \&do_sleep, rand(5) )->detach;
}

while (1) {
    select(undef, undef, undef, 0.3);
    if ( $cnt >= 10 ) {
        print "looping ...\n";
    }
    else {
        print "new threads ...\n";
        threads->new( \&do_sleep, rand(5) )->detach;
    }
}

sub do_sleep() {
    {
        lock $cnt;
        $cnt++;
    }

    my $time = shift;
    print "new thread:". threads->self->tid . "\n";
    print "cnt: " . $cnt, "\n";
    select(undef, undef, undef, $time);

    {
        lock $cnt;
        $cnt--;
    }
}
